public class Solution {
    public static String reverseWords(String s) {
        int len = s.length();
        s = reverse(s,0,len - 1);
        int left = 0,right = 0;
        int index = 0;
        while (index < len) {
            while (index < len && s.charAt(index) != ' ') {
                index++;
            }
            right = index - 1;
            s = reverse(s,left,right);
            left = index + 1;
            index++;
        }
        int slow = 0;
        int fast = 0;
        char[] array = s.toCharArray();
        for (fast = 0; fast < len; fast++) {
            if (array[fast] != ' ') {
                if (slow != 0) {
                    array[slow++] = ' ';
                }
                while (fast < len && array[fast] != ' ') {
                    array[slow++] = array[fast++];
                }
            }
        }
        char[] tmp = new char[slow];
        for (int i = 0; i < slow; i++) {
            tmp[i] = array[i];
        }
        return new String(tmp);
    }
    public static String reverse(String s,int begin,int end) {
        char[] array = s.toCharArray();
        while (begin < end) {
            char tmp = array[begin];
            array[begin]  = array[end];
            array[end] = tmp;
            begin++;
            end--;
        }
        return new String(array);
    }

    public static void main(String[] args) {
        String s = "  world   hello  ";
        s = reverseWords(s);
        System.out.println(s);
    }
}